package server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import communication.ClientComm;
import communication.ServerComm;

public class ServerClientCommSocketStream implements Runnable, ServerComm {
	private final Thread connThread;
	private final Server server;
	private final Socket socket;
	private BufferedWriter msgToClient;
	private BufferedReader msgFromClient;
	
	public ServerClientCommSocketStream(Socket socket, Server server, int num) {
		this.server = server;
		this.socket = socket;
		try {
			msgToClient = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			msgFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		connThread =  new Thread(this, ("ServerClient" + num));
		connThread.start();
	}
	
	@Override
	public void run() {
		String msg;
		try {
			while ((msg = msgFromClient.readLine()) != null) {
				new MsgInterpreter(this, server, msg);
			}
		} catch(Exception e){
			e.printStackTrace();
		}		
	}

	@Override
	public void msgToClient(String msg) {
		try{
			msgToClient.write(msg);
			msgToClient.newLine();
			msgToClient.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void msgFromClient(String msg){}
	@Override
	public void cambioTurno(String username) {}
	@Override
	public void connect(ClientComm cl) {}

	@Override
	public void close() {
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void closeAll() {}
}
